import os
from git import Repo

project_name = "ops-platform"
git_address = "ssh://git@localhost:3118/heyajun/ops-platform.git"
project_path = "/opt/data/projectData"

if os.path.exists(os.path.join(project_path, project_name)) is False:
    code_repo = Repo.clone_from(url=git_address, to_path=os.path.join(project_path, project_name), branch="1.0.0")
local_repo = Repo(os.path.join(project_path, project_name))
remote = local_repo.remote()
remote.fetch()
remote.pull()
# 当前分支
branch = local_repo.active_branch
print(branch.name)
# 所有分支
branch_data = local_repo.git.execute("git branch -r", shell=True)
all_branchs = [line.split('/')[-1] for line in branch_data.split('\n')]
branchs_list = list(set(all_branchs))
print(branchs_list)
# 切换分支
try:
    switch_branch = local_repo.git.execute("git checkout -f 1.0.1", shell=True)
except Exception as e:
    raise e
else:
    local_repo.git.execute("git pull", shell=True)
    print(switch_branch)
# 合并分支
try:
    local_repo.git.execute("git checkout -f 1.0.2", shell=True)
    # local_repo.git.execute(f"git add {os.path.join(project_path, project_name)}", shell=True)
    # local_repo.git.execute("git commit -m 'merge 1.0.2 to 1.0.0'", shell=True)
    local_repo.git.execute("git pull", shell=True)
except Exception as e:
    raise e
else:
    try:
        local_repo.git.execute("git checkout -f 1.0.0", shell=True)
        local_repo.git.execute("git merge 1.0.2", shell=True)
        merge_push = local_repo.git.execute("git push", shell=True)
    except Exception as e:
        raise e
    else:
        print(merge_push)


